package com.yida.wy.basic.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yida.common.core.constant.CacheConstants;
import com.yida.common.core.constant.HttpStatus;
import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.request.PullCompanyDataRequest;
import com.yida.common.core.text.Convert;
import com.yida.common.core.utils.HttpApiUtil;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.core.web.domain.AjaxResult;
import com.yida.common.redis.service.RedisService;
import com.yida.system.api.RemoteEsbRequestLogService;
import com.yida.system.api.constants.EsbRequestLogConstants;
import com.yida.system.api.domain.EsbRequestLog;
import com.yida.system.api.enums.SysDataPutInConfigEnum;
import com.yida.system.api.vo.SysDataPutInInterfaceVO;
import com.yida.wy.basic.consant.WyInitApiParamsConstant;
import com.yida.wy.basic.domain.dto.WyInitApiBuildDTO;
import com.yida.wy.basic.domain.dto.WyInitApiHouseDTO;
import com.yida.wy.basic.domain.dto.WyInitApiOwnerDTO;
import com.yida.wy.basic.domain.dto.WyInitApiProjectDTO;
import com.yida.wy.basic.domain.request.WyInitApiRequest;
import com.yida.wy.basic.service.IWyInitApiService;
import com.yida.wy.common.constant.WyInterfaceCodeConstants;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 这个可能需要重新开发20231118
 * 
 * 拉取基础数据Service业务层处理
 *
 * @author lqq
 * @date 2022-11-15
 */
@Service
public class WyInitApiServiceImpl implements IWyInitApiService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private RemoteEsbRequestLogService remoteEsbRequestLogService;

    private static final Logger log = LoggerFactory.getLogger(WyInitApiServiceImpl.class);

    /**
     * 拉取项目信息
     *
     * @param request 请求参数
     * @return /
     */
    @Override
    public List<WyInitApiProjectDTO> getCommunity(WyInitApiRequest request) {
        // 获取系统编码和接口地址
        Map<String, Object> map = new HashMap<String, Object>(16);
        // 接口请求参数字段
        map.put(WyInitApiParamsConstant.EFFECTIVE, 1);
        map.put(WyInitApiParamsConstant.COMMUNITY_PROJECT_NAME, request.getProjectName());
        map.put(WyInitApiParamsConstant.COMMUNITY_COMPANY_NAME, request.getCompanyName());
        map.put(WyInitApiParamsConstant.INTERFACE_CODE, WyInterfaceCodeConstants.EDA001);
        // 请求接口数据
        String r = sendRequest(WyInterfaceCodeConstants.EDA001, map, String.valueOf(request.getAreaId()));
        AjaxResult result = JSONUtil.toBean(r, AjaxResult.class);
        if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.ERROR)) {
            throw new ServiceException(result.get(AjaxResult.MSG_TAG).toString());
        }
        List<WyInitApiProjectDTO> dtos = new ArrayList<WyInitApiProjectDTO>();
        if (StringUtils.isNull(result.get(AjaxResult.DATA_TAG))) {
            return dtos;
        }
        JSONArray data = JSONUtil.parseArray(result.get(AjaxResult.DATA_TAG));
        data.forEach(o -> {
            JSONObject object = (JSONObject)o;
            WyInitApiProjectDTO dto = JSONUtil.toBean(object, WyInitApiProjectDTO.class);
            dtos.add(dto);
        });
        return dtos;
    }

    /**
     * 拉取楼栋信息信息
     *
     * @param request 请求参数
     * @return /
     */
    @Override
    public List<WyInitApiBuildDTO> getBuild(WyInitApiRequest request) {
        // 获取系统编码和接口地址
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put(WyInitApiParamsConstant.EFFECTIVE, 1);
        map.put(WyInitApiParamsConstant.BUILD_HOUSE_TYPE, "别墅,住宅");
        map.put(WyInitApiParamsConstant.BUILD_PROJECT_CODE, StringUtils.isNull(request.getProjectCode()) ? "" : request.getProjectCode());
        map.put(WyInitApiParamsConstant.BUILD_BUILD_CODE, StringUtils.isNull(request.getBuildCode()) ? "" : request.getBuildCode());
        map.put(WyInitApiParamsConstant.INTERFACE_CODE, WyInterfaceCodeConstants.EDA002);
        // 请求接口数据
        String r = sendRequest(WyInterfaceCodeConstants.EDA002, map, String.valueOf(request.getAreaId()));
        AjaxResult result = JSONUtil.toBean(r, AjaxResult.class);
        if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.ERROR)) {
            throw new ServiceException(result.get(AjaxResult.MSG_TAG).toString());
        }
        List<WyInitApiBuildDTO> dtos = new ArrayList<WyInitApiBuildDTO>();
        if (StringUtils.isNull(result.get(AjaxResult.DATA_TAG))) {
            return dtos;
        }
        JSONArray data = JSONUtil.parseArray(result.get(AjaxResult.DATA_TAG));
        data.forEach(o -> {
            JSONObject object = (JSONObject)o;
            WyInitApiBuildDTO dto = JSONUtil.toBean(object, WyInitApiBuildDTO.class);
            dtos.add(dto);
        });
        return dtos;
    }

    /**
     * 拉取房屋信息信息
     *
     * @param request 请求参数
     * @return /
     */
    @Override
    public List<WyInitApiHouseDTO> getHouse(WyInitApiRequest request) {
        // 获取系统编码和接口地址
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put(WyInitApiParamsConstant.EFFECTIVE, 1);
        map.put(WyInitApiParamsConstant.HOUSE_BUILD_CODE, request.getBuildCode());
        map.put(WyInitApiParamsConstant.INTERFACE_CODE, WyInterfaceCodeConstants.EDA003);
        // 请求接口数据
        String r = sendRequest(WyInterfaceCodeConstants.EDA003, map, String.valueOf(request.getAreaId()));
        AjaxResult result = JSONUtil.toBean(r, AjaxResult.class);
        if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.ERROR)) {
            throw new ServiceException(result.get(AjaxResult.MSG_TAG).toString());
        }
        List<WyInitApiHouseDTO> dtos = new ArrayList<WyInitApiHouseDTO>();
        Object obj = result.get(AjaxResult.DATA_TAG);
        if (StringUtils.isNull(obj)) {
            return dtos;
        }
        JSONArray data = JSONUtil.parseArray(obj);
        data.forEach(o -> {
            JSONObject object = new JSONObject(o, false);
            WyInitApiHouseDTO dto = JSONUtil.toBean(object, WyInitApiHouseDTO.class);
            dtos.add(dto);
        });
        return dtos;
    }

    /**
     * 拉取业主信息信息
     *
     * @param request 请求参数
     * @return /
     */
    @Override
    public List<WyInitApiOwnerDTO> getOwner(WyInitApiRequest request) {
        // 获取系统编码和接口地址
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put(WyInitApiParamsConstant.OWNER_HOUSE_CODE, request.getHouseCode());
        map.put(WyInitApiParamsConstant.INTERFACE_CODE, WyInterfaceCodeConstants.EDA004);
        // 请求接口数据
        String r = sendRequest(WyInterfaceCodeConstants.EDA004, map, String.valueOf(request.getAreaId()));
        AjaxResult result = JSONUtil.toBean(r, AjaxResult.class);
        if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.ERROR)) {
            throw new ServiceException(result.get(AjaxResult.MSG_TAG).toString());
        }
        List<WyInitApiOwnerDTO> dtos = new ArrayList<WyInitApiOwnerDTO>();
        Object obj = result.get(AjaxResult.DATA_TAG);
        if (StringUtils.isNull(obj)) {
            return dtos;
        }
        JSONArray data = JSONUtil.parseArray(obj);
        data.forEach(o -> {
            JSONObject object = new JSONObject(o, false);
            WyInitApiOwnerDTO dto = JSONUtil.toBean(object, WyInitApiOwnerDTO.class);
            dtos.add(dto);
        });
        // 查询业主电话号码
        dtos.forEach(owner -> {
            if (StringUtils.isNotBlank(owner.getCardNum())) {
                owner.setOwnerPhone(getOwnerPhone(owner.getCardNum().split(","), String.valueOf(request.getAreaId())));
            }
        });
        return dtos;
    }

    private String getOwnerPhone(String[] cardNums, String requestFlag) {
        // 获取系统编码和接口地址
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put(WyInitApiParamsConstant.OWNER_IPHONE_CARD_NUMS, cardNums);
        map.put(WyInitApiParamsConstant.INTERFACE_CODE, WyInterfaceCodeConstants.EDA005);
        // 请求接口数据
        String r = sendRequest(WyInterfaceCodeConstants.EDA005, map, requestFlag);
        AjaxResult result = JSONUtil.toBean(r, AjaxResult.class);
        if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.ERROR)) {
            throw new ServiceException(result.get(AjaxResult.MSG_TAG).toString());
        }
        String phone = Convert.toStr(result.get(AjaxResult.DATA_TAG), "");
        if (StringUtils.isBlank(phone)) {
            return phone;
        }
        // 处理空格和特殊符号替换为,
        String pattern = "[!|@|#|$|%|^|&|*|(|)|_|+|=|{|}|:|\"|<|>|?|\\[|\\]|;|'|.|/|！|@|#|￥|%|…|…|&|*|（|）|+|：|“|《|》|？|=|【|】|；|‘|，|。|、|’|`|~|·]";
        phone = phone.replaceAll("\\s{2,}", ",").replaceAll(pattern, ",");
        // 转出数组并去重
        String[] phoneArr = Convert.toStrArray(phone.trim());
        List<String> phones = Arrays.stream(phoneArr).filter(p -> StringUtils.isNotBlank(p)).distinct().collect(Collectors.toList());
        return StringUtils.join(phones, ",");
    }

    /**
     * 发送请求
     *
     * @param interfaceCode 接口编号
     * @param map 请求参数
     * @return
     */
    private String sendRequest(String interfaceCode, Map<String, Object> map, String requestFlag) {
        // 查询配置信息
        String key = CacheConstants.SYS_DATA_PUT_IN + CacheConstants.REDIS_SUFFIX + SysDataPutInConfigEnum.GWJ_INIT_CONFIG.getType() + CacheConstants.REDIS_SUFFIX + interfaceCode;
        SysDataPutInInterfaceVO sysDataPutInInterfaceVO = redisService.getCacheObject(key);
        if (ObjectUtil.isEmpty(sysDataPutInInterfaceVO)) {
            throw new ServiceException("未配置数据接入接口配置");
        }
        String url = sysDataPutInInterfaceVO.getIpUrl() + sysDataPutInInterfaceVO.getInterfaceUri();
        PullCompanyDataRequest request = new PullCompanyDataRequest();
        request.setCompanyId(sysDataPutInInterfaceVO.getCompanyId());
        request.setDockingInterfaceConfigId(sysDataPutInInterfaceVO.getDockingInterfaceConfigId());
        request.setRequestParams(map);
        request.setRequestFlag(requestFlag);
        // 发送请求
        String result = "";
        try {
            result = HttpApiUtil.sendGwjPostRequest(url, sysDataPutInInterfaceVO.getPublicKey(), sysDataPutInInterfaceVO.getPrivateKey(), request);
        } catch (Exception e) {
            // result = JSONUtil.toJsonStr(e);
            log.error("GwjInitApiServiceImpl.sendRequest error", e);
            throw new ServiceException("GwjInitApiServiceImpl.sendRequest error:" + e.getMessage());
        } finally {
            // 新增企业总线请求日志
            EsbRequestLog esbRequestLog = new EsbRequestLog();
            esbRequestLog.setUrl(url);
            esbRequestLog.setRequestParams(JSONUtil.toJsonStr(request));
            esbRequestLog.setTitle(EsbRequestLogConstants.PULL_GWJ_DATA);
            esbRequestLog.setDockingInterfaceConfigId(sysDataPutInInterfaceVO.getDockingInterfaceConfigId());
            esbRequestLog.setResponse(result);
            JSONObject jsonObject = StringUtils.isEmpty(result) ? new JSONObject() : JSONUtil.parseObj(result);
            // JSONObject jsonObject = JSONUtil.parseObj(result);
            if (ObjectUtil.isNotEmpty(jsonObject)) {
                esbRequestLog.setResponeId(String.valueOf(ObjectUtil.isEmpty(jsonObject.get(EsbRequestLogConstants.RESPONSE_ID)) ? null : jsonObject.get(EsbRequestLogConstants.RESPONSE_ID)));
            }
            remoteEsbRequestLogService.innerSave(esbRequestLog, SecurityConstants.INNER);
        }
        return result;
    }

    public static void main(String[] args) {
        // String result = "{\"userId\":1}";
        // String result = "";
        String result = null;
        // JSONObject jsonObject = StringUtils.isNull(result) ? new JSONObject() : JSONUtil.parseObj(result);
        JSONObject jsonObject = StringUtils.isEmpty(result) ? new JSONObject() : JSONUtil.parseObj(result);
        System.out.println("jsonObject：" + jsonObject);
        if (ObjectUtil.isNotEmpty(jsonObject)) {
            System.out.println(1);
        }
    }
}
